package com.tomtop.core.dorequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;

import com.fasterxml.jackson.core.type.TypeReference;
import com.tomtop.core.utils.JSONUtils;
import com.tomtop.core.utils.ObjectUtils;

public final class HttpContext{ 
	
	private final static Logger LOGGER = LoggerFactory.getLogger(HttpContext.class);
	
    static ThreadLocal<HttpContext> httpresponses=new ThreadLocal<HttpContext>(){protected HttpContext initialValue() {return new HttpContext(null,null);};};
    public static HttpContext getCurrentResponse() {
    	return httpresponses.get();
	}
    
    public HttpContext(RequestEntity<?> request, ResponseEntity<String> response2) {
    	this.request=request;
    	this.response=response2;
    	httpresponses.set(this);
	}
    
	private RequestEntity<?> request;
	private ResponseEntity<String> response;
	
	public RequestEntity<?> getRequest() {
		return request;
	}
	
	public ResponseEntity<String> getResponse() {
		return response;
	}
	/**
	 * 根据响应code判断是否响应成功，只有响应码等于200时才会成功
	 * @return
	 */
	public boolean isOk(){
		return  ObjectUtils.isNotNull(
					()->response,
					()->response.getStatusCode()
				)
				&&
				(
					response.getStatusCode().is1xxInformational()
					||
					response.getStatusCode().is2xxSuccessful()
					||
					response.getStatusCode().is3xxRedirection()
				);
	}
	/**
	 * 把响应结果以字符串的方式输出，
	 * @return
	 */
	public String getBody(){
		if(ObjectUtils.isNull(()->response )&&!response.hasBody())
			return null;
    	return response.getBody();
	}
	public <T> T getBodyToObject(TypeReference<T> typereference) {
		if(isOk()){
			String body=getBody();
			if(LOGGER.isDebugEnabled())
				LOGGER.debug("响应报文提数据:{}",body);
			return JSONUtils.fromObject(body, typereference);
		}
		return null;
	}
	public void close() {
		
	}
}